#!/bin/bash
set -e

source $(dirname $0)/version

ARCH=${ARCH:-"amd64"}
SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH:-"v2.3-dev"}
SUFFIX=""
[ "${ARCH}" != "amd64" ] && SUFFIX="_${ARCH}"

cd $(dirname $0)/../package

TAG=${TAG:-${VERSION}${SUFFIX}}
REPO=${REPO:-rancher}

if echo $TAG | grep -q dirty; then
    TAG=dev
fi

if [ -n "$DRONE_TAG" ]; then
    TAG=$DRONE_TAG
fi

cp ../bin/rancher ../bin/agent .

IMAGE=${REPO}/rancher:${TAG}
AGENT_IMAGE=${REPO}/rancher-agent:${TAG}

if [ ${ARCH} == arm64 ]; then
    sed -i -e '$a\' -e 'ENV ETCD_UNSUPPORTED_ARCH=arm64' Dockerfile
fi

docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} --build-arg IMAGE_REPO=${REPO} --build-arg SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH} -t ${IMAGE} .
docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} -t ${AGENT_IMAGE} -f Dockerfile.agent .
echo ${IMAGE} > ../dist/images
echo ${AGENT_IMAGE} >> ../dist/images
echo Built ${IMAGE} #${AGENT_IMAGE}
echo

cd ../bin
mkdir -p /tmp/system-charts && git clone --branch $SYSTEM_CHART_DEFAULT_BRANCH https://github.com/rancher/system-charts /tmp/system-charts
TAG=$TAG REPO=${REPO} go run ../pkg/image/export/main.go /tmp/system-charts $IMAGE $AGENT_IMAGE
